package com.xxg.renrenuser.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Indexes;
import com.xxg.renrencommon.domain.bean.UserSpreadBenefitInfo;
import com.xxg.renrencommon.domain.filedenum.userenum.BenefitStatusEnum;
import com.xxg.renrenuser.dao.bean.UserBankCardInfo;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.*;

/**
 * 收益dao
 *
 * @author szj
 * @date 2021/12/20
 */
@Repository
public class UserSpreadBenefitInfoDao {
    private final MongoTemplate mongoTemplate;

    public UserSpreadBenefitInfoDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "userSpreadBenefitInfo";
        MongoCollection<Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(UserSpreadBenefitInfo.class);
            createIndex(collection);
        }
    }

    /**
     * 创建索引
     *
     * @param collection 数据集
     */
    private void createIndex(MongoCollection<Document> collection) {
        collection.createIndex(Indexes.descending("orderId"));
        collection.createIndex(Indexes.descending("userId"));
        collection.createIndex(Indexes.descending("afterSalesOrderId"));
        collection.createIndex(Indexes.compoundIndex(Indexes.descending("userId"), Indexes.descending("orderId")));
        collection.createIndex(Indexes.compoundIndex(Indexes.descending("userId"), Indexes.descending("afterSalesOrderId")));
        collection.createIndex(Indexes.compoundIndex(Indexes.descending("userId"), Indexes.descending("benefitStatus")));
    }

    public List<UserSpreadBenefitInfo> findByUserId(Integer userId) {
        Query query = new Query(where("userId").is(userId));
        return mongoTemplate.find(query, UserSpreadBenefitInfo.class);
    }

    public List<UserSpreadBenefitInfo> findByUserIdAndStatus(Integer userId, Integer status) {
        Query query = new Query(where("userId").is(userId));
        query.addCriteria(where("benefitStatus").is(status));
        return mongoTemplate.find(query, UserSpreadBenefitInfo.class);
    }

    public List<UserSpreadBenefitInfo> findByUserIdAndOrderIdListAndStatus(Integer userId, List<String> orderIds, int benefitStatus) {
        Query query = new Query(where("userId").is(userId).and("orderId").in(orderIds).and("benefitStatus").is(benefitStatus));
        return mongoTemplate.find(query, UserSpreadBenefitInfo.class);
    }
}
